package kr.co.handysoft.common.compress;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

import net.sf.json.JSONObject;

public class Archiving {

	public static byte[] compress(String src)  throws IOException{
		byte[] dataByte = src.getBytes();
		
		Deflater deflater = new Deflater();
		
		deflater.setLevel(Deflater.BEST_COMPRESSION);
		deflater.setInput(dataByte);
		deflater.finish();
		
		ByteArrayOutputStream bao = new ByteArrayOutputStream(dataByte.length);
		byte[] buf = new byte[1024];
		while(!deflater.finished()) {
			int compByte = deflater.deflate(buf);
			bao.write(buf, 0, compByte);
		}
		
		bao.close();
		deflater.end();
		
		return bao.toByteArray();
	}
	
	public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
 		Inflater inflater = new Inflater();
		inflater.setInput(data);
		
		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		while(!inflater.finished()) {
			int compByte = inflater.inflate(buf);			
			bao.write(buf, 0, compByte);
		}
		bao.close();
		
		inflater.end();

		return bao.toByteArray();
	}
	
	public static byte[] hexToByteArray(String hex) {

	    if (hex == null || hex.length() == 0) {
	        return null;
	    }

	    byte[] ba = new byte[hex.length() / 2];
	    for (int i = 0; i < ba.length; i++) {
	        ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
	    }

	    return ba;
	}

	public static String byteArrayToHex(byte[] ba) {

	    if (ba == null || ba.length == 0) {
	        return null;
	    }

	    StringBuffer sb = new StringBuffer(ba.length * 2);
	    String hexNumber;
	    
	    for (int x = 0; x < ba.length; x++) {
	        hexNumber = "0" + Integer.toHexString(0xff & ba[x]);
	        sb.append(hexNumber.substring(hexNumber.length() - 2));
	    }

	    return sb.toString();

	}

	public static String send(String invoke) {
		String retString = null;
		try {
			retString = Archiving.byteArrayToHex(Archiving.compress(invoke));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return retString;
	}

	public static String get(String json, String key) {
		JSONObject jObj = JSONObject.fromObject(json);
		String hexString = jObj.getString(key);
		String retString = null;
		try {
			retString = new String(Archiving.decompress(Archiving.hexToByteArray(hexString)));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DataFormatException e) {
			e.printStackTrace();
		}
		return retString;
	} 
}
